package jobhunter.controller;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;

import jobhunter.model.User;
import jobhunter.repository.UserRepository;
import jobhunter.security.SecurityService;
import jobhunter.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;


@Controller
public class SecurityController 
{
	
	@Autowired	private UserService userService;
	@Autowired private UserRepository userRepository;

    @Autowired SecurityService loginService;

    @RequestMapping(value = "/login")
    public String signin(HttpServletRequest request) 
    {
        return "security/login";
    }

    @RequestMapping("/loginsubmit")
    public @ResponseBody String loginSubmit(
            @RequestParam(value= "username") String userName,
            @RequestParam(value= "password") String password) 
    {
        //TODO that's work?
        /*User user = null;
        user = */
        loginService.login(userName, password);  
        return "";
    }


    @RequestMapping("/logout")
    public String logout(WebRequest request)
    {  
        loginService.logout();
        return "redirect:/";
    }
	
	@RequestMapping(value = "/admin**", method = RequestMethod.GET)
	public ModelAndView adminPage() 
	{ 
		ModelAndView model = new ModelAndView();
		model.addObject("title", "Spring Security Custom Login Form");
		model.addObject("message", "This is protected page!");
		model.setViewName("security/admin"); 
		return model; 
	}
	
	
	@RequestMapping("/signin")
	public ModelAndView signIn()
	{
		ModelAndView mav = new ModelAndView("security/signin");
		return mav;
	}

	@RequestMapping("/signinvalidation")
	public String addActionValidate(@RequestParam(value = "login") String login,
			@RequestParam(value = "password") String password) throws UnsupportedEncodingException
	{
		login = new String(login.getBytes("ISO-8859-1"),"UTF-8");
		
		if(userRepository.findByLogin(login)==null)
		{
			userService.add(login, password);

			return "redirect:home";
		}
		else
		{
			return "redirect:signin";
		}
	}
}